//
//  ReaderBookModel.m
//  ebook
//
//  Created by 吴超飞 on 16/2/26.
//  Copyright © 2016年 Moton. All rights reserved.
//

#import "ReaderBookModel.h"
#import "EbookNetRequest.h"
#import "FmdbAccess.h"
#import "FileManager.h"
#import "DownloadManager.h"
#import "SSZipArchive.h"

@interface ReaderBookModel (){
    int beforeRetry,afterRetry;
}

@property (strong, atomic) __block NSMutableArray *beforeArray;
@property (strong, atomic) __block NSMutableArray *afterArray;

@end

@implementation ReaderBookModel

/*isMiddleIn 是否从某一章直接初始化 中间进入时直接读取该章节数据、不要取上次的历史位置
 */
-(instancetype) initWithBook:(Book*)book isMiddleIn:(BOOL)ismid{
    
    self = [super init];
    
    if(self){
        
        self.readerBook = [[ReaderBook alloc] init];
        self.readerBook.book = book;
        self.readerBook.currentChaptercontent.bookid = book.bookid;
        
        [[FmdbAccess shareModel] getRecordBooknode:book.bookid complete:^(Bookmark *booknode) {
            if (!ismid && booknode) {
                
                self.readerBook.chapterId = booknode.chapterid;
                self.readerBook.booknodePercent = [booknode.percent floatValue];
            }else{
                self.readerBook.chapterId = book.firstchapterid;
                self.readerBook.booknodePercent = 0.0f;
            }
        }];
    }
    return self;
}
    
-(void) getBookmarkContent:(Bookmark *)mark complete:(BookTextCompletion)textBlock{
    
    Chapter *chapter = [[Chapter alloc] init];
    chapter.chapterid = mark.chapterid;
    chapter.chaptername = mark.chaptername;
    [self getChapterContent:chapter forceUpdate:NO complete:^(ChapterContent *chaptercontent,NSArray *pageArray,TurnResult result) {
        textBlock(chaptercontent,result);
    }];
}
    
#pragma mark - 章节内容
-(void) getChapterContentType:(ContentType)type forceUpdate:(BOOL)update complete:(BookTextCompletion)textBlock{
    
    [self getChapterList:^(NSMutableArray *list) {//内容基于章节列表获取，所以首先要保证获取到了完整的章节列表
        if(!list||list.count==0){
            if(textBlock)textBlock(nil,TurnNoNet);
            return ;
        }
        
        Chapter *chapter = nil;
        switch (type) {
            case CURRENTCHAPTERCONTENT:
            chapter = self.readerBook.chapter;
            break;
            case PRECHAPTERCONTENT:
            chapter = self.readerBook.preChapter;
            break;
            case NEXTCHAPTERCONTENT:
            chapter = self.readerBook.nextChapter;
            break;
            default:
            break;
        }
        
        if (!chapter) {//不存在的章节（第一章前或最后一章后）
            if(textBlock)textBlock(nil,TurnNoMore);
            return;
        }
        
        [self getChapterContent:chapter forceUpdate:update complete:^(ChapterContent *chaptercontent,NSArray *pageArray,TurnResult result) {
            switch (type) {
                case CURRENTCHAPTERCONTENT:
                self.readerBook.currentChaptercontent = chaptercontent;
                break;
                case PRECHAPTERCONTENT:
                self.readerBook.preChaptercontent = chaptercontent;
                break;
                case NEXTCHAPTERCONTENT:
                self.readerBook.nextChaptercontent = chaptercontent;
                break;
                default:
                break;
            }
            
            if(textBlock)textBlock(chaptercontent,result);
        }];
    }];
}
    
    //获取数据并分页
-(void)getChapterContent:(Chapter *)chapter forceUpdate:(BOOL)update complete:(BookTextPageCompletion)pageBlock{
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __strong Chapter *chapter_copy = chapter;
        ChapterContent *chaptercontent = [ChapterContent new];
        chaptercontent.bookid = self.readerBook.book.bookid;
        chaptercontent.chapterid = chapter_copy.chapterid;
        chaptercontent.chaptername = chapter_copy.chaptername;
        chaptercontent.sourceurl = chapter_copy.sourceurl;
        
        NSString *content = nil;
        //获取数据前先判断本地是否有，有就直接取本地
        NSString *localChaptercontent = [FileManager readContentBook:self.readerBook.book chapterId:chapter_copy.chapterid];
        if(localChaptercontent&&!update&&![[DownloadManager shareInstance] isErrorContent:localChaptercontent]){//不是强制刷新的情况下才取本地数据
            content = localChaptercontent;
        }else{
            content = [[DownloadManager shareInstance] getNetChaptercontent:self.readerBook.book chapter:chapter];
        }
        
        chaptercontent.chaptercontent = content;
        NSArray *pageArray = [[ReaderGlobalModel shareModel] pagingText:chaptercontent.chaptercontent];
        dispatch_async(dispatch_get_main_queue(), ^{
            TurnResult result = TurnSuc;
            if([[DownloadManager shareInstance] isErrorContent:content])
            result = TurnNoNet;
            __strong ChapterContent *chapContent = chaptercontent;
            if(pageBlock)pageBlock (chapContent,pageArray,result);
        });
    });
}

//判断是否需要更新章节列表文件
-(BOOL)needUpdateChapterlistFile{
    
    Book *localbook = [FileManager readBookinfo:self.readerBook.book];
    if(localbook.bookname.length>0)self.readerBook.book.bookname = localbook.bookname;
    NSArray *localArray = [FileManager readChapterlist:self.readerBook.book];
    NSInteger updatetime = [self.readerBook.book.updatetime integerValue];
    if ((updatetime>0&&updatetime!=[localbook.updatetime integerValue])||!localArray||localArray.count == 0) {
        return YES;
    }
    return NO;
}
    
#pragma mark - 章节列表
    //获取章节列表，本地有就本地读取，没有就网络获取
-(void)getChapterList:(void(^)(NSMutableArray *list))complete{
    
    if(complete&&self.readerBook.chapterList.count>0){
        complete(self.readerBook.chapterList);
        return;
    }
    
    //    dispatch_async(dispatch_get_global_queue(0, 0), ^{//DES解密在子线程中闪退，注释该行
    NSArray *localArray = [FileManager readChapterlist:self.readerBook.book];
    if ([self needUpdateChapterlistFile]) {//本地更新时间是旧的或本地列表是空的则从网路获取数据
        [self getNetChapterList:^(NSArray *list) {
            __strong NSMutableArray *slist = [self dictListToChapterList:(list?list:localArray)];
            if(complete)
                complete(slist);
        }];
    }else{
        __strong NSMutableArray *slist = [self dictListToChapterList:localArray];
        if(complete)
            complete(slist);
    }
    //    });
}

//读取网络上的章节列表文件，并存储到本地
-(void)getNetChapterList:(void(^)(NSArray *list))complete{
    
    Book *book = self.readerBook.book;
    NSString *downurl = [self chapterlistUrl:book];
    NSString *directory = kBookDirectory(book.bookid,book.siteid);
    
    [EbookNetRequest downloadFileWithURLString:downurl downloadFileProgress:^(NSProgress *downloadProgress) {
    } saveToPath:directory downloadCompletionHandler:^(NSURL *filePath, NSError *error) {
        if(error){
            MTLog(@"获取网络章节列表失败，book:%@,%@",self.readerBook.book,error);
            if(complete)complete(nil);
            return ;
        }
        
        //        if([FileManager decryChapterlist:bookid]){
        //            __strong NSArray *chapterlist = [FileManager readChapterlist:bookid];
        //            Book *book = [FileManager readBookinfo:bookid];
        //            NSString *bookname = book.bookname;
        //            if(bookname.length>0)self.readerBook.book.bookname = bookname;
        //            dispatch_async(dispatch_get_main_queue(), ^{
        //                [[NSNotificationCenter defaultCenter] postNotificationName:kGetChapterListCompleteNotification object:@(YES)];
        //            });
        //            if(complete)complete(chapterlist);
        //        }
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            __strong NSArray *chapterlist = [FileManager readChapterlist:book];
            Book *mbook = [FileManager readBookinfo:book];
            NSString *bookname = mbook.bookname;
            if(bookname.length>0)self.readerBook.book.bookname = bookname;
            dispatch_async(dispatch_get_main_queue(), ^{
                [[NSNotificationCenter defaultCenter] postNotificationName:kGetChapterListCompleteNotification object:@(YES)];
            });
            if(complete)complete(chapterlist);
        });
    }];
}

//检查更新并获取获取章节列表
-(void)checkUpdateAndGetchapterlist:(void(^)(NSArray *list,BOOL needReload))complete{
    [EbookNetRequest checkBookUpdate:self.readerBook.book.bookid success:^(int stateCode, NSString *successMsg, NSDictionary *dict) {
        NSInteger updatetime = [dict[@"data"][@"lastUpdateTime"] integerValue];
        if(updatetime>0&&[self.readerBook.book.updatetime integerValue] != updatetime)
            [self getNetChapterList:^(NSArray *list) {
                complete(list,YES);
            }];
        else
            [self getChapterList:^(NSMutableArray *list) {
                complete(list,NO);
            }];
    } failed:^(int stateCode, NSString *failMsg) {
        [self getChapterList:^(NSMutableArray *list) {
            complete(list,NO);
        }];
    }];
}

//Dictionary类型的列表转为Chapter对象类型的列表
-(NSMutableArray *)dictListToChapterList:(NSArray *)array{
    
    NSMutableArray *list= [[DownloadManager shareInstance] dictListToChapterList:array];//章节列表和当前章赋值
    __weak typeof(self) weakSelf = self;
    [self.readerBook setChapterList:list complete:^(BOOL exist) {//赋值的同时获取当前章节
//        __strong __typeof(self) strongSelf = weakSelf;
//        dispatch_async(dispatch_get_main_queue(), ^{
//            //            if(!exist)
//            //            [[NSNotificationCenter defaultCenter] postNotificationName:kGetlastReadnodeFailedNotification object:strongSelf.readerBook.book];
//        });
    }];
    
    return list;
}

-(NSString *)chapterlistUrl :(Book *)book{
    
    if(!book||!book.bookid||!book.siteid)
        return nil;
    
    NSString *directory = [DownloadManager shareInstance].bookfileDirectory;
    NSString *format = @"%@/%@/%d/%@/chapterlist.zip?time=%d";
    int time = [self.readerBook.book.updatetime intValue];
    NSString *url = [NSString stringWithFormat:format,directory,book.siteid,[book.bookid intValue]/1000,book.bookid,time];
    url = [[DownloadManager shareInstance] cdnUrl:url];
    MTLog(@"chapterlistUrl:%@",url);
    
    return url;
}

#pragma mark -
    //判断当前章节是否本地已经存在了
-(BOOL)isExistCurrentChapter{
    
    return [self isCurrentBookExistLocalChapter:self.readerBook.chapterId];
}

//判断当前书中的某章节是否本地已经存在了
-(BOOL)isCurrentBookExistLocalChapter:(NSString*)chapterid{
    
    NSString *localChaptercontent = [FileManager readContentBook:self.readerBook.book chapterId:chapterid];
    if(localChaptercontent.length>0){
        return YES;
    }
    return NO;
}
    
-(void)resetChapterList{
    
    [self.readerBook.chapterList removeAllObjects];
}
    
-(void) getBookmarkList:(void(^)(NSArray *bookmarks))complete{
    
    if(!self.readerBook.bookmarkList)
    [[FmdbAccess shareModel] getBookmarkOfBook:self.readerBook.currentChaptercontent.bookid complete:^(NSMutableArray *books) {
        self.readerBook.bookmarkList = [NSMutableArray arrayWithArray:books];
        if(complete)complete(books);
    }];
    else
    if(complete)complete(self.readerBook.bookmarkList);
}
    
-(void)updateBookmarkList{
    
    [[FmdbAccess shareModel] getBookmarkOfBook:self.readerBook.currentChaptercontent.bookid complete:^(NSMutableArray *books) {
        self.readerBook.bookmarkList = [NSMutableArray arrayWithArray:books];
    }];
}
    
#pragma mark - 分页处理
    
    //获取初始化数据，以上次阅读位置为中心
-(void)getInitPageDataComplete:(PageDataCompletion)textBlock{
    
    [self getChapterList:^(NSMutableArray *list) {//内容基于章节列表获取，所以首先要保证获取到了完整的章节列表
        if(!list||list.count==0){
            textBlock(nil,TurnNoNet);
            return ;
        }
        
        Chapter *chapter = self.readerBook.chapter;
        if (!chapter) {//不存在的章节（第一章前或最后一章后）
            textBlock(nil,TurnNoMore);
            return;
        }
        [self pageDataCenterChapter:chapter forceUpdate:NO currentPageOrPercent:_readerBook.booknodePercent isPercent:YES complete:^(NSDictionary *dict) {
            TurnResult result = TurnSuc;
            //        if([self isNoContent:_readerBook.currentChaptercontent.chaptercontent])
            //            result = TurnNoNet;
            
            textBlock(dict,result);
        }];
    }];
}
    
-(void)pageDataCenterChapter:(Chapter *)chapter forceUpdate:(BOOL)update currentPageOrPercent:(float) current isPercent:(BOOL)ispercent complete:(void(^)(NSDictionary *dict))complete{
    
    if(!_beforeArray)_beforeArray = [NSMutableArray array];
    if(!_afterArray)_afterArray = [NSMutableArray array];
    [_beforeArray removeAllObjects];
    [_afterArray removeAllObjects];
    beforeRetry=0;
    afterRetry=0;
    
    [self pageDataBeforeChapter:chapter forceUpdate:update currentPageOrPercent:current isPercent:ispercent complete:^{
        [self pageDataAfterChapter:chapter forceUpdate:update currentPageOrPercent:current isPercent:ispercent complete:^{
            
            NSInteger currentIndex = _beforeArray.count;
            NSMutableArray *dataArray = [NSMutableArray arrayWithArray:_beforeArray];
            [dataArray addObjectsFromArray:_afterArray];
            if(complete)complete([NSDictionary dictionaryWithObjectsAndKeys:dataArray,@"data",@(currentIndex),@"index", nil]);
        }];
    }];
}
    
-(void)pageDataBeforeChapter:(Chapter *)chapter forceUpdate:(BOOL)update currentPageOrPercent:(float) current isPercent:(BOOL)ispercent complete:(void(^)(void))complete{
    
    if(!chapter){
        MTLog(@"pageDataBeforeChapter chapter=nil");
        return;
    }
    
    [self getChapterContent:chapter forceUpdate:update complete:^(ChapterContent *chaptercontent,NSArray *pageArray,TurnResult result) {//先从本章内部开始取
        
        //        __strong ChapterContent *chaptercontent = chaptercontent0;
        NSInteger currentPage = current;
        if(current!=-1)//只获取第一次的内容作为当前页
        _readerBook.currentChaptercontent = chaptercontent;//上下翻页需要用到该数据
        
        if(ispercent)//传递的是百分比，先换算成页码
        currentPage = (int)(pageArray.count*current+0.5);//四舍五入取整
        else
        currentPage = current;
        
        if(current==-1)//跨章取前一章时从最后一页开始取
        currentPage=pageArray.count;
        
        NSInteger size = HALFSIZE;
        while (_beforeArray.count<size && --currentPage>=0) {//从后往前取数据(不包括当前)
            PageData *data= [[PageData alloc]init];
            data.text = [chaptercontent.chaptercontent substringWithRange:NSRangeFromString(pageArray[currentPage])];
            data.chapter = chapter;
            data.currentPage = currentPage;
            data.totalPage = pageArray.count;
            [_beforeArray insertObject:data atIndex:0];//依次往前插入对象
        }
        
        if(_beforeArray.count<size){//不足则递归向前获取上一章
            if (beforeRetry++<size/2) {//防止无数据死循环，限制递归次数
                Chapter *preChapter = [_readerBook chapterBefore:chapter];
                if(preChapter)//第一章前面没有，不要获取
                [self pageDataBeforeChapter:preChapter forceUpdate:update currentPageOrPercent:-1 isPercent:NO complete:complete];
                else{
                    if(complete)complete();
                }
            }else{
                if(complete)complete();
            }
        }else{
            if(complete)complete();
        }
    }];
}
    
-(void)pageDataAfterChapter:(Chapter *)chapter forceUpdate:(BOOL)update currentPageOrPercent:(float) current isPercent:(BOOL)ispercent complete:(void(^)(void))complete{
    
    if(!chapter)return;
    [self getChapterContent:chapter forceUpdate:update complete:^(ChapterContent *chaptercontent,NSArray *pageArray,TurnResult result) {//先从本章内部开始取
        
        //        __strong ChapterContent *chaptercontent = chaptercontent0;
        NSInteger currentPage = 0;
        if(ispercent)//传递的是百分比，先换算成页码
        currentPage = (int)(pageArray.count*current+0.5);//四舍五入取整
        else
        currentPage = current;
        
        if(current==-1)currentPage=0;//跨章时从第一页开始取
        
        NSInteger size = HALFSIZE*2+1;//包含当前对象，所以要加一
        while (_afterArray.count<size && currentPage++<pageArray.count) {//依次往后取数据(包括当前)
            PageData *data= [[PageData alloc]init];
            data.text = [chaptercontent.chaptercontent substringWithRange:NSRangeFromString(pageArray[currentPage-1])];
            data.chapter = chapter;
            data.currentPage = currentPage-1;
            data.totalPage = pageArray.count;
            [_afterArray addObject:data];//依次往后插入当前页后面的对象
        }
        
        if(_afterArray.count<size){//数据不足则递归获取下一章的
            if (afterRetry++<size/2) {//防止无数据时死循环，限制递归次数
                Chapter *nextChapter = [_readerBook chapterAfter:chapter];
                if(nextChapter){
                    [self pageDataAfterChapter:nextChapter forceUpdate:update currentPageOrPercent:-1 isPercent:NO complete:complete];
                }else{
                    if(complete)complete();
                }
            }else{
                if(complete)complete();
            }
        }else{
            if(complete)complete();
        }
    }];
}
    
    @end
